import TcpServer, { ServerOptions } from "./tcpServer";
import { ISignaLightRunConfig } from "../../renderer/src/interface";
import { BrowserWindow } from "electron";

export interface IsignaLightStatus extends ISignaLightRunConfig {
  phaseTime: number;
  rtc: string;
  status: number[];
}

export default class C3ProtocolHandler extends TcpServer {
  private curStatus: IsignaLightStatus = {} as IsignaLightStatus;
  private window: BrowserWindow = {} as BrowserWindow;
  constructor(option: ServerOptions, window: BrowserWindow) {
    super(option);
    this.window = window;
  }

  protected handleData(clientId: string, data: Buffer): void {
    console.log(`from_C3 ${clientId} data: ${data.toString("hex")}`);

    if (
      data.toString("hex").length === 48 &&
      data.toString("hex").slice(0, 14) === "0d0a1400c7ffff"
    ) {
      //实时状态
      this.handleRealTimeStatus(data);
    }
  }

  private handleRealTimeStatus(data: Buffer) {
    const devDate = new Date((data.readUint32LE(7) + 946944000) * 1000);
    //const devDateStr = `${devDate.getUTCFullYear()}-${devDate.getUTCMonth()+1}-${devDate.getDate()} ${devDate.getUTCHours()}:${devDate.getUTCMinutes()}:${devDate.getUTCSeconds()}`;
    this.curStatus.rtc = devDate.toISOString().slice(0, 19).replace("T", " "); //devDateStr;
    //阶段时间
    this.curStatus.phaseTime = data[12];
    //倒计时
    this.curStatus.time = data[21];
    //4个方向状态数组
    this.curStatus.status = [data.readUint16LE(13)];
    this.curStatus.status.push(data.readUint16LE(15));
    this.curStatus.status.push(data.readUint16LE(17));
    this.curStatus.status.push(data.readUint16LE(19));
    this.window.webContents.send("update-status", this.curStatus);
  }
}
